package rjeutsky.servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import rjeutsky.ControllerWrapper;
import rjeutsky.models.Subscription;
import rjeutsky.models.User;

/**
 * Servlet implementation class PaySubscriptionServlet
 */
@WebServlet("/PaySubscription")
public class PaySubscriptionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PaySubscriptionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User currentUser = (User) request.getSession().getAttribute("currentUser");
		if (currentUser != null && ControllerWrapper.getApplicationController().checkIsAdmin(currentUser)) {
			Subscription subscription;
			try {
				Long id = Long.parseLong(request.getParameter("id"));
				subscription = ControllerWrapper.getApplicationController().getSubscription(id);
				if (subscription == null) {
					response.sendError(404);
					return;
				}
			} catch (NumberFormatException ex) {
				response.sendError(404);
				return;
			}
			
			try {
				ControllerWrapper.getApplicationController().processPayment(subscription);
			} catch (SQLException e) {
				response.sendError(500);
				e.printStackTrace();
				return;
			} 
			response.sendRedirect("Subscriptions.jsp?infoText=Payment+has+been+processed+successfully");
		}
		else {
			response.sendRedirect("Login.jsp");
		}
	}

}
